package wht.jly.forum.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * 属性工具类
 * 获取对象所有的非空属性
 *
 * @author lanyangji
 */
public class PropertyUtils {

    private PropertyUtils() {
    }


    /**
     * 获取对象的所有属性值为空的属性名，并以字符串数组的形式返回
     *
     * @param source 对象
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            if (src.isReadableProperty(pd.getName()) && src.isWritableProperty(pd.getName())) {
                Object srcValue = src.getPropertyValue(pd.getName());
                if (srcValue == null) {
                    emptyNames.add(pd.getName());
                }
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

}
